package com.wm.blog_gateway.auth;

import com.alibaba.fastjson.JSONObject;
import com.wm.blog_common.constatnt.ErrorConstant;
import com.wm.blog_common.result.Result;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

/***
 * @ClassName: CustomAuthenticationEntryPoint
 * @Description: 未登录处理
 * @Author: 半卷流年
 * @Create_time: 18:19 2020-3-30
 */
@Component
@Slf4j
@NoArgsConstructor
public class CustomAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type", "application/json; charset=UTF-8");
        String body = JSONObject.toJSONString(Result.failure(ErrorConstant.ADMIN_NOT_LOGIN,"请登录"));
        try {
            DataBuffer buffer = response.bufferFactory().wrap(body.getBytes("utf-8"));
            return response.writeWith(Mono.just(buffer));
        } catch (UnsupportedEncodingException ex) {
            log.error("未登录处理异常",ex);
        }
        return null;
    }
}
